# -*- coding: utf8 -*-
import json
import time
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from libs.mypthon.oss_info import ossinfo


def fileTrans(akId, akSecret, appKey, fileLink,savefilename,max_single_segment_time,callBackfun_progress=None) :
    '''
    阿里云的录音文件识别
    :param akId: str
    :param akSecret: str
    :param appKey: str
    :param fileLink: str
    :param savefilename: str
    :param max_single_segment_time: 允许单句话最大结束时间，最小值5000(int
    :param callBackfun_progress:function 回调函数
    :return: bool,err_info
    '''
    err_info=[]
    # 地域ID，固定值。
    REGION_ID = "cn-shanghai"
    PRODUCT = "nls-filetrans"
    DOMAIN = "filetrans.cn-shanghai.aliyuncs.com"
    API_VERSION = "2018-08-17"
    POST_REQUEST_ACTION = "SubmitTask"
    GET_REQUEST_ACTION = "GetTaskResult"
    # 请求参数
    KEY_APP_KEY = "appkey"
    KEY_FILE_LINK = "file_link"
    KEY_VERSION = "version"
    KEY_ENABLE_WORDS = "enable_words"
    # 是否将大于16kHz采样率的音频进行自动降采样（降为16kHz），默认为false，开启时需要设置version为“4.0”
    KEY_ENABLE_SAMPLE_RATE_ADAPTIVE='enable_sample_rate_adaptive'
    # 是否打开ITN，中文数字将转为阿拉伯数字输出，默认值为false，开启时需要设置version为“4.0”。
    ENABLE_INVERSE_TEXT_NORMALIZATION='enable_inverse_text_normalization'
    KEY_SENTENCES='Sentences'
    # 是否开启智能分轨
    KEY_AUTO_SPLIT = "auto_split"
    # 允许单句话最大结束时间，最小值5000，默认值14000。单位为毫秒。(Integer)
    KEY_max_single_segment_time='max_single_segment_time'
    # 响应参数
    KEY_TASK = "Task"
    KEY_TASK_ID = "TaskId"
    KEY_STATUS_TEXT = "StatusText"
    KEY_RESULT = "Result"
    # 状态值
    STATUS_SUCCESS = "SUCCESS"
    STATUS_RUNNING = "RUNNING"
    STATUS_QUEUEING = "QUEUEING"
    # 创建AcsClient实例
    client = AcsClient(akId, akSecret, REGION_ID)
    # 提交录音文件识别请求
    postRequest = CommonRequest()
    postRequest.set_domain(DOMAIN)
    postRequest.set_version(API_VERSION)
    postRequest.set_product(PRODUCT)
    postRequest.set_action_name(POST_REQUEST_ACTION)
    postRequest.set_method('POST')
    # 新接入请使用4.0版本，已接入（默认2.0）如需维持现状，请注释掉该参数设置。
    # 设置是否输出词信息，默认为false，开启时需要设置version为4.0。
    task = {KEY_APP_KEY : appKey, KEY_FILE_LINK : fileLink, KEY_VERSION : "4.0", KEY_ENABLE_WORDS : False,KEY_ENABLE_SAMPLE_RATE_ADAPTIVE:True,ENABLE_INVERSE_TEXT_NORMALIZATION:True,KEY_max_single_segment_time:max_single_segment_time}
    # 开启智能分轨，如果开启智能分轨，task中设置KEY_AUTO_SPLIT为True。
    # task = {KEY_APP_KEY : appKey, KEY_FILE_LINK : fileLink, KEY_VERSION : "4.0", KEY_ENABLE_WORDS : False, KEY_AUTO_SPLIT : True}
    task = json.dumps(task)
    print(task)
    postRequest.add_body_params(KEY_TASK, task)
    taskId = ""
    try :
        postResponse = client.do_action_with_exception(postRequest)
        postResponse = json.loads(postResponse)
        print (postResponse)
        err_info.append(str(postResponse))
        statusText = postResponse[KEY_STATUS_TEXT]
        if statusText == STATUS_SUCCESS :
            if callBackfun_progress!=None:
                callBackfun_progress('','录音文件识别:',"录音文件识别请求成功响应")
            print ("录音文件识别请求成功响应！")
            taskId = postResponse[KEY_TASK_ID]
        else :
            print ("录音文件识别请求失败！")
            if callBackfun_progress!=None:
                callBackfun_progress('','录音文件识别:',"录音文件识别请求失败")
            return False,err_info
    except ServerException as e:
        print (e)
        err_info.append(e)
    except ClientException as e:
        print (e)
        err_info.append(e)
    # 创建CommonRequest，设置任务ID。
    getRequest = CommonRequest()
    getRequest.set_domain(DOMAIN)
    getRequest.set_version(API_VERSION)
    getRequest.set_product(PRODUCT)
    getRequest.set_action_name(GET_REQUEST_ACTION)
    getRequest.set_method('GET')
    getRequest.add_query_param(KEY_TASK_ID, taskId)
    # 提交录音文件识别结果查询请求
    # 以轮询的方式进行识别结果的查询，直到服务端返回的状态描述符为"SUCCESS"、"SUCCESS_WITH_NO_VALID_FRAGMENT"，
    # 或者为错误描述，则结束轮询。
    statusText = ""
    while True :
        try :
            getResponse = client.do_action_with_exception(getRequest)
            getResponse = json.loads(getResponse)
            print (getResponse)
            statusText = getResponse[KEY_STATUS_TEXT]
            if statusText == STATUS_RUNNING :
                # 继续轮询
                if callBackfun_progress != None:
                    callBackfun_progress('','录音文件识别:','正在识别中...')
                time.sleep(10)
            elif statusText == STATUS_QUEUEING:
                if callBackfun_progress != None:
                    callBackfun_progress('','录音文件识别:','识别任务排队中...')
                time.sleep(10)
            else :
                # 退出轮询
                break
        except ServerException as e:
            print (e)
            err_info.append(str(e))
        except ClientException as e:
            print (e)
            err_info.append(str(e))
    if statusText == STATUS_SUCCESS :
        print ("录音文件识别成功！")
        # print(getResponse[KEY_RESULT])
        '''
                {'Sentences': [
                    {'EndTime': 4510, 'SilenceDuration': 1, 'BeginTime': 1270, 'Text': 'College English test band 6. ',
                     'ChannelId': 0, 'SpeechRate': 92, 'EmotionValue': 6.3},
                    {'EndTime': 8080, 'SilenceDuration': 0, 'BeginTime': 4800, 'Text': 'Part 2 listening comprehension. ',
                     'ChannelId': 0, 'SpeechRate': 73, 'EmotionValue': 6.3}]}
        '''
        with open(file=savefilename,mode='w+',encoding='utf-8') as file:
            list_str=str(getResponse[KEY_RESULT][KEY_SENTENCES])
            file.write(list_str)
        return True,[]
    else :
        print ("录音文件识别失败！")
        return False,err_info


if __name__ == '__main__':
    oss=ossinfo('LTAI5t7Eihxxxxxxxxxxxxx34BKH','4nC52DprzwYxxxxxxxxxxxtUl9R','oss-cn-beijing.xxxxx.com','1xxxx045','xxxxx')

    accessKeyId = oss.id
    accessKeySecret =oss.secret
    appKey =oss.appKey

    fileLink = "https://18xxxxxxxxxxxxng.aliyuncs.com/jingting_tempfiles/test1.mp3"
    # ossutil.uploadAudioFilesToAlibabaCloud('F:/test1.mp3','LTAI5t7xxxxx9y34BKH','4nC52DprzwYSrxxxxxxxxktUl9R','oss-cn-beixxxxxxxxcs.com','1xxxxx3045')

    # 执行录音文件识别
    fileTrans(accessKeyId, accessKeySecret, appKey, fileLink,'F:/test.txt',7000)